<?php

$db = new Database();
$auth = Auth::getAuth('current_user');

$data = json_decode($_POST["data"], true);

foreach ($data as $request) {
    $formObject = new Form($db, $request["FormID"]);
    $myRequest = new Request();
    $fields = array();

    $myRequest->load($formObject->id, $request["ID"]);
    $fields['Node_ID'] = $request["Node_ID"];
    $fields['Workflow_ID'] = $request["Workflow_ID"];

    if ($request["Node_ID"] == 'Cancel') {
        $fields['Status'] = 'Cancelled';
        $fields['Processor'] = '';
        $fields['LastAction'] = '';
    }

    if ($request["Node_ID"] == 'Save' || $request["Node_ID"] == 'Cancel') {
        $logDoc = new Request_Log($db);
        $logDoc->form = new Form($db, $request["FormID"]);
        $logDoc->request_id = $request["ID"];

        if ($request["Node_ID"] == 'Save') {
            $logDoc->details = 'Saved';
        } else {
            $logDoc->details = 'Cancelled';
        }

        $logDoc->created_by = new Person($db, $auth['id']);
        $logDoc->date_created = $date;
        $logDoc->save();
    }
    
    $myRequest->data = $fields;
    $myRequest->modify();

    if ($request["Node_ID"] != 'Save' && $request["Node_ID"] != 'Cancel') {
        $myRequest->processWF();
    }
//print_r($request);
    //echo 'Request has been processed';
}
?>
